package com.example.sale.dao;

import com.example.sale.entity.SaleChance;
import com.example.sale.entity.SalePlan;
import com.example.system.entity.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.jdbc.SQL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@Mapper
@Repository
public interface PlanDAO {
    Logger logger = LoggerFactory.getLogger(PlanDAO.class);

    /*关联查询 结果集  必须给定 List<Map> */
    @SelectProvider(type = PlanDAOProvider.class, method = "queryData")
    List<Map> queryData(String id)throws Exception;

    /*查询data_dic全部数据，后期使用 pagehelper 做分页处理*/
    @Select("select * from sale_chance ")
    List<SaleChance> queryDataAll();

    @Select("select * from sales_plan where cus_id = #{id}")
    List<SalePlan> queryByCusId(String id);

    @Select("select * from sales_plan where id = #{id}")
    SalePlan queryPlanById(String id);

    @Delete("delete from sales_plan where id = #{id}")
    void deleteInfo(String id);

    /* 内部类实现 update*/
    @UpdateProvider(type = PlanDAOProvider.class, method = "updateInfo")
     void updateInfo(SalePlan salePlan);

    @InsertProvider(type = PlanDAOProvider.class, method = "saveInfo")
   // @Options(useGeneratedKeys = true, keyProperty = "saleChance.id",keyColumn = "saleChance.id")
    void saveInfo(SaleChance saleChance, HttpServletRequest request);

    @Insert("insert into sales_plan(cus_id,plan_date,plan_desc,notes) values(#{cus_id},#{plan_date},#{plan_desc},#{notes})")
    void savePlan(SalePlan salePlan);

    //内部类实现动态sql
    class PlanDAOProvider {

        /*自定义SQL实现关联查询 --> 可以直接定义String sql ="" 而无需使用一下SQL 关键字拼接*/
        public String queryData(String id){
            //结构化sql
           /* FROM和WHERE：跟SELECT一样，可以写多个参数，也可以在多行重复使用，最终会智能合并而不会报错
            这样语句适用于写很长的SQL时，能够保证SQL结构清楚。便于维护，可读性高。*/
            return new SQL(){
                {
                SELECT("chance.id,customer_name,summarize,linkman");
                SELECT("link_tel,create_time,creator,opportunity_desc");
                SELECT("opportunity_source,success_probability");  //会智能合并
                SELECT("designator,assignment_time,status");
                SELECT("plan.plan_date,plan_desc,plan.id as pid");
                    FROM("sale_chance chance");
                    LEFT_OUTER_JOIN("sales_plan plan  on chance.id = plan.cus_id ");
                    if(!StringUtils.isEmpty(id)){
                        WHERE("chance.id = "+id+" ");
                    }
                }
            }.toString();
        }

        public String updateInfo(SalePlan salePlan){
            return new SQL(){
                {
                    UPDATE("sales_plan");
                    if (!StringUtils.isEmpty(salePlan.getPlan_desc())) {
                        SET("plan_desc= #{plan_desc,javaType=String,jdbcType=VARCHAR}");
                    }
                    if (!StringUtils.isEmpty(salePlan.getExecutive_effect())) {
                        SET("executive_effect= #{executive_effect,javaType=String,jdbcType=VARCHAR}");
                    }
                    if (!ObjectUtils.isEmpty(salePlan.getNotes())) {
                        SET("notes= #{notes,javaType=String,jdbcType=VARCHAR}");
                    }
                        SET("plan_date= now()");

                    WHERE("id = #{id,javaType=String,jdbcType=VARCHAR}" );
                }
            }.toString();

        }

        public String saveInfo(SaleChance saleChance, HttpServletRequest request){
           String sql =  new SQL(){
               {
                   INSERT_INTO("sale_chance");

                   if (!StringUtils.isEmpty(saleChance.getCustomer_name())) {
                       VALUES("customer_name"," '"+saleChance.getCustomer_name()+"'");
                   }
                   if (!StringUtils.isEmpty(saleChance.getSummarize())) {
                       VALUES("summarize"," '"+saleChance.getSummarize()+"'");
                   }
                   if (!ObjectUtils.isEmpty(saleChance.getLinkman())) {
                       VALUES("linkman"," '"+saleChance.getLinkman()+"'");
                   }
                   if (!StringUtils.isEmpty(saleChance.getLink_tel())) {
                       VALUES("link_tel"," '"+saleChance.getLink_tel()+"'");
                   }
                   if (!StringUtils.isEmpty(saleChance.getCreate_time())) {
                       VALUES("create_time"," '"+saleChance.getCreate_time()+"'");
                   }else{
                       VALUES("create_time","now()");
                   }
                   if (!StringUtils.isEmpty(saleChance.getCreator())) {
                       VALUES("creator"," '"+saleChance.getCreator()+"'");
                   }else{
                       User user = (User)request.getSession().getAttribute("user");
                       VALUES("creator"," '"+user.getUser_name()+"'");
                   }
                   if (!StringUtils.isEmpty(saleChance.getOpportunity_desc())) {
                       VALUES("opportunity_desc"," '"+saleChance.getOpportunity_desc()+"'");
                   }
                   if (!StringUtils.isEmpty(saleChance.getOpportunity_source())) {
                       VALUES("opportunity_source"," '"+saleChance.getOpportunity_source()+"'");
                   }
                   if (!StringUtils.isEmpty(saleChance.getSuccess_probability())) {
                       VALUES("success_probability"," '"+saleChance.getSuccess_probability()+"'");
                   }
                   if (!StringUtils.isEmpty(saleChance.getDesignator())) {
                       VALUES("designator"," '"+saleChance.getDesignator()+"'");
                   }
                   if (!StringUtils.isEmpty(saleChance.getAssignment_time())) {
                       VALUES("assignment_time"," '"+saleChance.getAssignment_time()+"'");
                   }else{
                       VALUES("assignment_time","now()");
                   }
                   if (!StringUtils.isEmpty(saleChance.getStatus())) {
                       VALUES("status"," '"+saleChance.getStatus()+"'");
                   }
               }
           }.toString();
           logger.info("saveInfo:-->",sql);
            return sql;
        }
    }

}
